﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Imaging;

namespace GW2LastOnline.Controls
{
    class ProgressSwirl : Control
    {
        private const int FRAMES = 9;
        private const int FRAME_WIDTH = 64;
        private const int FRAME_HEIGHT = 64;
        private const int INITIAL_FRAME = 4;

        private Image frames;
        private int frame;
        private bool disposed;

        public ProgressSwirl()
        {
            this.frames = Properties.Resources.loading;
            this.frame = INITIAL_FRAME;

            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        }

        protected override void OnCreateControl()
        {
            base.OnCreateControl();
            if (!this.DesignMode)
                new Thread(new ThreadStart(Animate)).Start();
        }

        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);

            if (!this.Visible)
                frame = INITIAL_FRAME;
        }
        
        private void Animate()
        {
            while (!disposed)
            {
                if (this.Visible && this.Enabled)
                {
                    frame = (frame + 1) % FRAMES;
                    this.Invalidate();
                }
                Thread.Sleep(120);
            }
        }

        public new int Width
        {
            get
            {
                return base.Width;
            }
            set
            {
                base.Width = value;
                base.Height = value;
            }
        }

        public new int Height
        {
            get
            {
                return base.Height;
            }
            set
            {
                base.Width = value;
                base.Height = value;
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Graphics g = e.Graphics;
            Rectangle dest = new Rectangle(0, 0, this.Width, this.Height);
            Rectangle src = new Rectangle();

            src.X = 0;
            src.Width = FRAME_WIDTH;
            src.Height = FRAME_HEIGHT;

            src.Y = frame * FRAME_HEIGHT;
            g.DrawImage(frames, dest, src, GraphicsUnit.Pixel);
        }

        protected override void Dispose(bool disposing)
        {
            this.disposed = true;
            base.Dispose(disposing);
        }
    }
}
